<template>
  <el-dialog :title="title" :visible.sync="visible" width="600px" :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
      <el-form-item label="姓名" prop="personnelId">
        <el-select @change="(e) => listenChoosePerson(e)" v-model="ruleForm.personnelId"
          :disabled="dialogType == 'look'" placeholder="请选择" clearable filterable class="input-w300">
          <el-option v-for="item in userList" :key="item.id"
            :value="item.id">
            {{ item.personnelName }}{{ item.unitFullName ? '-' + item.unitFullName : '' }}
          </el-option>

        </el-select>
      </el-form-item>
      <el-form-item label="性别" v-if="personInfo.gender">
        <span v-if="personInfo.gender == 1">男</span>
        <span v-else-if="personInfo.gender == 2">女</span>
        <span v-else>未知</span>

      </el-form-item>
      <el-form-item label="年龄" v-if="personInfo.age">
        {{ personInfo.age }}
      </el-form-item>
      <el-form-item label="专业" v-if="personInfo.majorCode">
        {{ selectDictLabel(dict.type.sys_user_major_code, personInfo.majorCode,) }}
      </el-form-item>
      <el-form-item label="单位" v-if="personInfo.unitFullName">
        {{ personInfo.unitFullName }}
      </el-form-item>
      <el-form-item label="技能名称" prop="skillName">
        <el-input :disabled="dialogType == 'look'" v-model.trim="ruleForm.skillName" placeholder="请输入" clearable
          class="input-w300" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="技能等级" prop="skillLevel">
        <el-select :disabled="dialogType == 'look'" v-model="ruleForm.skillLevel" placeholder="请选择" clearable filterable
          class="input-w300">
          <el-option v-for="dict in dict.type.sys_skill_level" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="单位" prop="certificationMechanism">
        <treeselect disabled class="input-w300" v-model="ruleForm.certificationMechanism"
          :options="deptOptions" :show-count="true" placeholder="请选择" />
      </el-form-item> -->
      <el-form-item label="证书照片">
        <el-upload :disabled="dialogType == 'look'" ref="uploadImg" class="upload-demo" :limit="3"
          list-type="picture-card" :action="fileAction" :headers="fileHeaders" :file-list="fileList"
          :before-upload="beforeFileUpload" :on-success="handleFileSuccess" :on-remove="handleRemove">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">只能上传图片，且不超过10M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" v-if="dialogType != 'look'">
      <el-button type="primary" @click="confirmForm('ruleForm')">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDeptName } from "@/utils/ruoyi";
import { deptTree, } from "@/api/org";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addSkillManagement, findUserList, updateSkillManagement, getDetail } from "@/api/skill";
import { getToken } from "@/utils/auth";

export default {
  components: {
    Treeselect
  },
  dicts: ['sys_position_type', 'sys_skill_level','sys_user_major_code'],
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    dialogType: {
      default: '',
      type: String
    },
    id: {
      default: '',
      type: String
    },
    title: {
      default: '',
      type: String
    }
  },
  computed: {
    downloadUrl() {
      return process.env.VUE_APP_DOWNLOAD_URL
    },
  },
  data() {
    return {
      personInfo: {},
      userList: this.$store.state.user.userList,
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      deptOptions: [],
      fileList: [],
      personName: '',
      ruleForm: {
        skillName: '',
        skillLevel: '',
        personnelId: '',
      },
      rules: {
        skillName: [
          { required: true, message: '请输入技能名称', trigger: 'blur' },
          { max: 50, message: '长度在 50 个字符内', trigger: 'blur' }
        ],
        skillLevel: [
          { required: true, message: '请选择技能等级', trigger: 'blur' },
        ],
        personnelId: [
          { required: true, message: '请选择人员', trigger: 'blur' },
        ],
        certificationMechanism: [
          { required: true, message: '请选择部职别', trigger: 'blur' },
        ],
      }
    };
  },
  computed: {
    deptList() {
      return this.$store.state.user.deptList
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.ruleForm = {
          skillName: '',
          skillLevel: '',
          personnelId: '',
          certificationMechanism: null,
          certificatePic: '',
        }
        this.personName = '';
        this.fileList = []
        if (this.id) {
          this.getSkillInfo()
        }
      } else {
        this.fileList = []
      }
    }
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    getDeptName(id) {
      return getDeptName(this.deptList, id)
    },
    listenChoosePerson(val) {
      let item = this.userList.find(e => e.id == val)
      console.log(item);
      this.personInfo = item || {}
      this.ruleForm.certificationMechanism = this.userList.find(e => e.id == this.ruleForm.personnelId).unitCode
    },
    /** 查询单位下拉树结构 */
    getDeptTree() {
      deptTree().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 获取技能详情
    async getSkillInfo() {
      let res = await getDetail(parseInt(this.id));
      if (res.code == 200) {
        this.ruleForm.skillLevel = String(res.data.skillLevel);
        this.ruleForm.personnelId = res.data.personnelId;
        this.ruleForm.skillName = res.data.skillName;
        this.ruleForm.certificationMechanism = res.data.certificationMechanism;
        this.personName = res.data.personnelName;
        if (res.data.certificatePic) {
          let list = res.data.certificatePic.split(',')
          this.fileList = list.map(item => {
            return {
              name: '',
              fileName: item,
              url: this.downloadUrl + item
            }
          })
        }
      } else {
        this.$message.error(res.msg)
      }
    },
    // 确认新增人员
    handleSelectChannel(val) {
      this.ruleForm.personnelId = val.id;
    },
    // 查询人员
    querySearchUser(val, cb) {
      this.debounceFun(async function () {
        let params = {
          keyword: val,
        }
        let res = await findUserList(params);
        if (res.code == 200) {
          if (res.rows) {
            res.rows.forEach((item) => {
              item.value = item.personnelName;
            })
          }
          cb(res.rows)
        } else {
          cb([])
        }
      }, 800)()
    },
    // 确认提交按钮
    async confirmForm(form) {

      this.$refs[form].validate(async (valid) => {
        if (!valid) return false;
        let params = {
          skillName: this.ruleForm.skillName,
          skillLevel: this.ruleForm.skillLevel,
          personnelId: this.ruleForm.personnelId,
          certificationMechanism: this.ruleForm.certificationMechanism,
        }
        if (this.fileList.length > 0) {
          params.certificatePic = this.fileList.map(item => item.fileName).join(',')
        }
        let res = null;
        if (this.id) {
          params.id = this.id;
          res = await updateSkillManagement(params)
        } else {
          res = await addSkillManagement(params)
        }
        if (res.code == 200) {
          this.$message.success('新增成功')
          this.handleClose();
        } else {
          this.$message.error(res.msg)
        }
      })


    },
    // 文件上传前检查
    beforeFileUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 150;
      const fileTypeList = ['jpg', 'jpeg', 'png']
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleFileSuccess(res, file) {
      if (res.code === 200) {
        this.fileList.push({
          name: file.originalFilename,
          fileName: res.fileName,
          url: this.downloadUrl + res.fileName
        })
      }
    },
    // 文件删除
    handleRemove(file, fileList) {
      let index = fileList.indexOf(file);
      this.fileList.splice(index, 1)
    },
    // 取消
    handleCancel() {
      this.$emit('update:visible', false)
    },
    // 关闭
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },
    // 防抖函数
    debounceFun(func, delay) {
      let timer = null;
      return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    },
  }
};
</script>
<style lang='scss' scoped></style>